package wells.wellsim.transport;

import java.net.InetSocketAddress;

import ch.qos.logback.core.db.dialect.MsSQLDialect;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import wells.wellsim.handler.CustomChannelEventHandler;
import wells.wellsim.model.proto.MessageProto;

public class WellsImServer {
	public static void main(String[] args) {
		ServerBootstrap serverBootstrap = new ServerBootstrap();

		EventLoopGroup parentGroup = new NioEventLoopGroup();
		EventLoopGroup childGroup = new NioEventLoopGroup();
		serverBootstrap.group(parentGroup, childGroup);

		/*
		 * 在TCP/IP协议中，无论发送多少数据，总是要在数据前面加上协议头，同时，对方接收到数据，也需要发送ACK表示确认。为了尽可能的利用网络带宽，
		 * TCP总是希望尽可能的发送足够大的数据。这里就涉及到一个名为Nagle的算法，该算法的目的就是为了尽可能发送大块数据，避免网络中充斥着许多小数据块。
		 * 
		 * TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性，有数据发送时就马上发送，就将该选项设置为true关闭Nagle算法；
		 * 如果要减少发送次数减少网络交互，就设置为false等累积一定大小后再发送。默认为false。
		 */
		serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

		serverBootstrap.channel(NioServerSocketChannel.class);

		serverBootstrap.localAddress(new InetSocketAddress(23457));// 端口

		serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();

				pipeline.addLast(new LoggingHandler(LogLevel.INFO))
						// 11 秒没有向客户端发送消息就发生心跳
						.addLast(new IdleStateHandler(11, 0, 0))
						// google Protobuf 编解码
						.addLast(new ProtobufVarint32FrameDecoder())
						.addLast(new ProtobufDecoder(MessageProto.Message.getDefaultInstance()))
						.addLast(new ProtobufVarint32LengthFieldPrepender()).addLast(new ProtobufEncoder())
						.addLast(new CustomChannelEventHandler());
			}

		});

		try {
			ChannelFuture sync = serverBootstrap.bind().sync();

			sync.addListener(future -> {
				if (future.isSuccess()) {
					System.out.println("启动成功……");
				}
			});

			if (sync.isSuccess()) {
				System.out.println("netty websocket server 启动完毕...");
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
